<?php
namespace App\Repositories;

use App\Repositories\BaseRepository;
use App\User;
use Identicon\Identicon;

class UserRepository {
	use BaseRepository;

	protected $model, $table_name;

	public function __construct(User $user) {
		$this->model = $user;
		$this->table_name = 'users';
	}

	protected function searchColumn($query, $where) {
		return $query->when(array_key_exists('email', $where), function ($query) use ($where) {
			return $query->where('email', 'like', "%{$where['email']}%");
		})->when(array_key_exists('name', $where), function ($query) use ($where) {
			return $query->where('name', 'like', "%{$where['name']}%");
		})->when(array_key_exists('nick_name', $where), function ($query) use ($where) {
			return $query->where('nick_name', 'like', "%{$where['nick_name']}%");
		});
	}

	public function create(array $data) {
		return $this->model->create([
			'name' => $data['name'],
			'email' => $data['email'],
			'password' => $data['password'],
			'avatar' => (new Identicon())->getImageDataUri($data['name'], 256),
		]);
	}

	public function getUserByAccount($account) {
		return $this->model->where('email', $account)->orWhere('name', $account)->select('id', 'name', 'avatar')->firstOrFail();
	}

	public function getUserByEmail($email) {
		return $this->model->where('email', $email)->first();
	}

	public function getUserByName($name) {
		return $this->model->where('name', $name)->firstOrFail();
	}

	public function saveAvatar($id, $image) {
		$user = $this->getById($id);
		$storage_path = storage_path('app');
		$prefix_path = '/public/avatars/';

		//移动旧头像文件至旧头像文件夹
		$old_avatar_name = getFileName($user->avatar);
		moveFile($storage_path . $prefix_path . $old_avatar_name, $storage_path . '/avatars/' . $user->name . '/' . $old_avatar_name);

		$user->avatar = asset('storage/avatars/' . $image);
		$user->save();
		return $user->avatar;
	}
}